package com.woniuxy.tfss.web.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.tfss.entity.Admin;
import com.woniuxy.tfss.entity.Perms;
import com.woniuxy.tfss.entity.ResponseEntity;
import com.woniuxy.tfss.entity.RolePerm;
import com.woniuxy.tfss.jwt.Audience;
import com.woniuxy.tfss.jwt.JwtTokenUtil;
import com.woniuxy.tfss.mapper.AdminMapper;
import com.woniuxy.tfss.service.AdminService;
import com.woniuxy.tfss.service.PermsService;
import com.woniuxy.tfss.service.RolePermService;
import com.woniuxy.tfss.utils.MyUtils;
import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("admin")
@CrossOrigin
@Slf4j
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RolePermService rolePermService;
    @Autowired
    private PermsService permsService;
    @Autowired
    private Audience audience;

    /**
     * 登录方法
     * @param admin
     * @param request
     * @return
     */
    @PostMapping("login")
    @ResponseBody
    public ResponseEntity<?> login(@RequestBody Admin admin,HttpServletRequest request) {
        log.debug("账号{},密码{}", admin.getAccount(), admin.getPassword());
        //String password="9379b12a3972ec3a314cc52ac14a3196";//new SimpleHash("MD5",user.getPassword(),"tom",1024).toString();
        UsernamePasswordToken token = new UsernamePasswordToken(admin.getAccount(), admin.getPassword());
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(token);
            String adminId = currentUser.getSession().getAttribute("adminId").toString();
            String jwt = JwtTokenUtil.createJWT(adminId, audience);

            QueryWrapper wrapper=new QueryWrapper();
            wrapper.eq("id",adminId);
            Admin admin1=new Admin();
            admin1.setLastIp(MyUtils.getIp(request));
            admin1.setLastLogin(MyUtils.getNow());
            adminService.update(admin1,wrapper);
            return new ResponseEntity<>(jwt);
        } catch (UnknownAccountException uae) {
            System.out.println("账号不存在");
            return ResponseEntity.UNKNOWNACC;

        } catch (DisabledAccountException dae) {
            System.out.println("账号被冻结");
            return ResponseEntity.LOCKEDACC;
        }catch (IncorrectCredentialsException ice) {
            System.out.println("密码不正确");
            return ResponseEntity.WRONGPWD;
        }
    }

    /**
     *
     * 修改密码
     * @param oldPwd
     * @param newPwd
     * @param req
     * @return
     */
    @PostMapping("changePwd")
    @ResponseBody
    public ResponseEntity changePwd(String oldPwd, String newPwd, HttpServletRequest req){
       String token=req.getHeader("token");
       int id=Integer.parseInt(JwtTokenUtil.getadminId(token,audience.getBase64Secret()));
       Admin admin=adminService.getById(id);
       SimpleHash oldHash=new SimpleHash("MD5",oldPwd,admin.getAccount(),1024);
       if(!oldHash.toString().equals(admin.getPassword())){
           return ResponseEntity.WRONGPWD;
       }else{
           Admin admin1=new Admin();
           SimpleHash newHash=new SimpleHash("MD5",newPwd,admin.getAccount(),1024);
           admin1.setPassword(newHash.toString());
           QueryWrapper<Admin> wrapper=new QueryWrapper<>();
           wrapper.eq("id",id);
           adminService.update(admin1,wrapper);
           return ResponseEntity.SUCCESS;
       }
    }

    /**
     * 管理员多条件分页查询
     * @param account
     * @param roleId
     * @param createDate
     * @param status
     * @param page
     * @return
     */
    @GetMapping("listByPage")
    @ResponseBody
    public ResponseEntity<Page<Admin>> listByPage(String account,Integer[] roleId,String[] createDate,String status,Integer page){
        QueryWrapper<Admin> wrapper=new QueryWrapper<>();
        if(!StringUtils.isEmpty((account))){
            wrapper.like("account",account);
        }else if(roleId!=null && roleId.length!=0 ){
            for(Integer RoleId :roleId){
                wrapper.or().eq("roleId",RoleId);
            }
        }else if(!StringUtils.isEmpty((status))&& !"0".equals(status)){
            wrapper.eq("status", status);
        }else if(createDate.length!=0){
            wrapper.between("createDate",createDate[0],createDate[1]);
        }
       Page adminPage=new Page(page==null?1:page,3);
        return new ResponseEntity<>(adminService.page(adminPage,wrapper));
    }

    /**
     * 增加管理员
     * @param admin
     * @return
     */
    @PostMapping("add")
    @ResponseBody
    public ResponseEntity<Void> add(@RequestBody Admin admin){
        admin.setCreateDate(MyUtils.getNow());
        admin.setStatus("1");
        //将传进来的密码加密，存入数据库
        SimpleHash hash=new SimpleHash("MD5",admin.getPassword(),admin.getAccount(),1024);
        admin.setPassword(hash.toString());
        QueryWrapper<Admin> wrapper=new QueryWrapper<>();
        wrapper.eq("account",admin.getAccount());
        if(adminService.getOne(wrapper)==null){
            adminService.save(admin);
        }else{
            return ResponseEntity.EXISTACC;
        }
        return ResponseEntity.SUCCESS;
    }

    /**
     * 修改管理员信息
     * @param admin
     * @return
     */
    @PostMapping("update")
    @ResponseBody
    public ResponseEntity<Void> update(@RequestBody Admin admin){
        Admin admin1=new Admin();
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("id",admin.getId());
        if(admin.getPassword()!=null && !"".equals(admin.getPassword())){
            SimpleHash hash=new SimpleHash("MD5",admin.getPassword(),admin.getAccount(),1024);
            admin1.setPassword(hash.toString());
        }
        admin1.setRoleId(admin.getRoleId());
        adminService.update(admin1,wrapper);
        return  ResponseEntity.SUCCESS;
    }

    /**
     * 冻结管理员
     * @param id
     * @return
     */
    @GetMapping("changeStatus")
    @ResponseBody
    public  ResponseEntity<Void> changeStatus(Integer id){
       Admin admin=adminService.getById(id);
       QueryWrapper<Admin> wrapper=new QueryWrapper<>();
       wrapper.eq("id",id);

       if(Admin.NOMAL.equals(admin.getStatus())){
           admin.setStatus(Admin.LOCKED);
           admin.setLockTime(MyUtils.getNow());
           adminService.update(admin,wrapper);
       }else{
           admin.setStatus(Admin.NOMAL);
           adminService.unLock(admin);
       }
       return ResponseEntity.SUCCESS;
    }

    @GetMapping("getMenuById")
    @ResponseBody
    public ResponseEntity<List<Perms>> getMenuById(HttpServletRequest request){
        String token = request.getHeader("token");
        Integer id=Integer.parseInt(JwtTokenUtil.getadminId(token,audience.getBase64Secret()));
        Admin admin=adminService.getById(id);
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("roleId",admin.getRoleId());
        List<RolePerm>  rolePerms= rolePermService.list(wrapper);
        QueryWrapper<Perms> wrapper1=new QueryWrapper<>();
        rolePerms.forEach(r->{
            wrapper1.or().eq("id",r.getPermId());
            wrapper1.eq("type","m");
        });
        List<Perms> perms=permsService.list(wrapper1);
        return new ResponseEntity<>(perms);
    }
}
